package com.hyts.distlock.handler;

import com.hyts.distlock.config.LockConfig;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Optional;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.distlock.handler
 * author:Libo/Alex
 * create-date:2019-05-11 01:18
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: Jedis client factory handler class
 */
public class JedisHandler {

    /**
     * 构建一些基本的properties属性参数
     * @param maxConnectionSize
     * @param maxWaitTimeSeconds
     * @param maxIdleNum
     * @return
     */
    public static JedisPoolConfig properties(int maxConnectionSize,long maxWaitTimeSeconds,int maxIdleNum){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdleNum);
        config.setMaxTotal(maxConnectionSize);
        config.setMaxWaitMillis(maxWaitTimeSeconds);
        config.setTestOnBorrow(true);
        config.setTestOnCreate(true);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        return config;
    }
    /**
     * 构建Jedis数据连接池
     * @param jedisPoolConfig
     * @param host
     * @param port
     * @param timeout 单位为秒
     * @param password
     * @param database
     * @return
     */
    public static JedisPool build(JedisPoolConfig jedisPoolConfig,String host,Integer port
            ,Integer timeout,String password,Integer database){
        jedisPoolConfig = Optional.ofNullable(jedisPoolConfig).orElse(new JedisPoolConfig());
        host = Optional.ofNullable(host).orElse(LockConfig.DEFAULT_CONNECTION_HOST);
        port = Optional.ofNullable(port).orElse(LockConfig.DEFAULT_CONNECTION_PORT);
        timeout = Optional.ofNullable(timeout).orElse(LockConfig.REDIS_CONNECTION_TIMEOUT);
        database = Optional.ofNullable(database).orElse(LockConfig.REDIS_DATABASE_NO) ;
        return new JedisPool(jedisPoolConfig,host,port,timeout*1000,password,database);
    }

    public static JedisPool build(JedisPoolConfig jedisPoolConfig,String host,int port,int timeout,String password){
        return build(jedisPoolConfig,host,port,timeout,password);
    }

    public static JedisPool build(JedisPoolConfig jedisPoolConfig,String host,int port,int timeout){
        return build(jedisPoolConfig,host,port,timeout);
    }

    public static JedisPool build(JedisPoolConfig jedisPoolConfig,String host,int port){
        return build(jedisPoolConfig,host,port);
    }

    public static JedisPool build(JedisPoolConfig jedisPoolConfig,String host){
        return build(jedisPoolConfig,host,-1);
    }

    public static JedisPool build(JedisPoolConfig jedisPoolConfig){
        return build(jedisPoolConfig,null,-1);
    }
    public static JedisPool build(){
        return build(null);
    }
}
